
package com.diy.sigmund.diycommon.designpatterns.state;

import java.util.Random;

/**
 * @author ylm-sigmund
 * @since 2022/2/15 17:50
 */
public class HasQuarterState implements State {

    /** 增加一个随机数产生器，产生10%赢的机会 */
    Random random = new Random(System.currentTimeMillis());
    GumballMachine gumballMachine;

    public HasQuarterState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void insertQuarterState() {
        System.out.println("您已投钱，不能再投入另外的25分钱");
    }

    @Override
    public void ejectQuarterState() {
        System.out.println("退还25分钱");
        gumballMachine.setState(gumballMachine.getNoQuarterState());
    }

    @Override
    public void turnCrank() {
        System.out.println("你转动了曲柄");
        // 0-9
        int winner = random.nextInt(10);
        if (winner == 0 && gumballMachine.getCount() > 1) {
            // 10%的概率可以赢得一颗免费糖果
            gumballMachine.setState(gumballMachine.getWinnerState());
        } else {
            gumballMachine.setState(gumballMachine.getSoldState());
        }
    }

    @Override
    public void dispense() {
        System.out.println("没有糖果可以发放");
    }

    public static void main(String[] args) {
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            System.out.println(random.nextInt(10));
        }
    }
}
